import socket
import threading
import json
import os
import sys
import select

#这是单个客户端连接的服务端代码

FILE = os.path.abspath('./file')
sys.path.append(FILE)
import file as f


# 标志变量，用于通知线程退出
global exit_flag
exit_flag = False


#服务器文件缓存
global server_file_buff
server_file_buff={}



def server_send_data(data):
    global new_socket
    new_socket.send(data.encode())




#服务接收数据的处理
def server_receive_data_handle(buf):
    # print(buf)

    data = {}
    #尝试转为json
    try:
        data=json.loads(buf)
        print(data)
    except ValueError:
        print("not json")
        return 
    



#服务端接收处理线程
def server_receive_handle_thread():
    global new_socket,client_ip_port
    global server_socket
    
    while not exit_flag:
        #阻塞等待客户端连接
        state =True
        # readable, writable, exceptional = select.select(server_socket, [], [])
        # if readable is readable:
        #     new_socket, client_ip_port = server_socket.accept()
        #     print("成功")
        # else:
        #     print("fail")

        # try:
        #     print("123")
        #     server_socket.settimeout(2.0)
        #     new_socket, client_ip_port = server_socket.accept()
        #     state =True
        # except socket.timeout:
        #     state =False
        #     print("No client connected within 5 seconds.")
        new_socket, client_ip_port = server_socket.accept()
        if state == True:
            while not exit_flag:
                # 5 新的socket收信息
                buf = new_socket.recv(4096)
                if buf:
                    server_receive_data_handle(buf.decode())
                    # print(buf.decode())
                    # 6 新的socket发信息
                    # send_data = (f'{client_ip_port}连接成功').encode()
                    # new_socket.send(send_data)
                else:
                    global sub_thread
                    print(f'客户端{client_ip_port}断开连接')
                    # sys.exit(0)
                    break                    
            new_socket.close()
            break
        break
    sys.exit(0)


def server_init():
    global server_socket
    global sub_thread
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 2 绑定 IP 和端口
    # server_socket.bind(('电脑本机IP',8888))
    server_socket.bind(('',9999)) # 前面空，绑定服务器的任意一个网卡
    # 3 监听，参数是同时连接的客户端数量
    server_socket.listen(128)
    sub_thread = threading.Thread(target=server_receive_handle_thread  )
    sub_thread.start()


